import { ALL, Body, Config, Controller, Get, Inject, Post } from "@midwayjs/decorator";
import { JwtService } from "@midwayjs/jwt";
import { UserLoginDTO } from "../dto/user.dto";
import { UserModel } from '../model/user.model';

@Controller("/user")
export class UserController {

    @Config(ALL)
    config: any;

    @Inject()
    jwtService: JwtService;

    @Inject()
    userModel: UserModel;

    @Post("/login")
    async login(@Body(ALL) userLoginDTO: UserLoginDTO): Promise<any> {
        // console.log("this.config", this.config);
        //console.log("userLoginDTO", userLoginDTO);
        let r = await this.userModel.getUserByUsernameAndPassword(userLoginDTO.username, userLoginDTO.password);
        // console.log("r", r);
        if (r) {
            let payload = { secret: this.config.jwt.secret, expiresIn: this.config.jwt.expiresIn };
            // console.log("payload", payload);
            let jwtString = this.jwtService.signSync(payload);
            // console.log("jwtString", jwtString);
            let ret = {
                code: 200,
                result: "success",
                message: "登录成功",
                data: {
                    token: jwtString
                }
            };
            // console.log("ret", ret);
            return ret;
        } else {
            let ret = {
                code: 400,
                result: "error",
                message: "账号或密码不正确",
                data: null
            };
            // console.log("ret", ret);
            return ret;
        }
    }

@Get("/test")
async test() {
    return "hello,姚雄伟";
}

@Post("/decodeToken")
async decodeToken(@Body("token") token: string): Promise < any > {
    // console.log("token", token);
    let tokenObj = this.jwtService.decode(token);
    // console.log("tokenObj", tokenObj);
    return tokenObj;
}
}